/*
GORM 数据库操作
*/

package dbOperate

import (
	"fjj/tool/config"
	"fjj/tool/universal"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
)

func DbConn() *gorm.DB {

	cfg := config.GetConfig()

	connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=%s&parseTime=True&loc=Local", cfg.Database.User, cfg.Database.Password, cfg.Database.Host, cfg.Database.Port, cfg.Database.Dbname, cfg.Database.Charset)
	fmt.Println(connArgs)

	db, err := gorm.Open(cfg.Database.Driver, connArgs)
	if err != nil {
		fmt.Println("本次未获取到mysql连接")
		panic(err)
	}

	db.SingularTable(true) //如果使用gorm来帮忙创建表时，这里填写false的话gorm会给表添加s后缀，填写true则不会
	db.LogMode(true)       //打印sql语句
	//开启连接池
	db.DB().SetMaxIdleConns(100)   //最大空闲连接
	db.DB().SetMaxOpenConns(10000) //最大连接数
	db.DB().SetConnMaxLifetime(30) //最大生存时间(s)

	return db
}

//测试
func DpOperate() {
	conn := DbConn()
	defer conn.Close()

	//自动迁移,数据库结构可适应结构而自动增加列，旧有列不会减
	conn.AutoMigrate(&UserInfo{})

	//创建记录
	u1 := UserInfo{15, "小米", "男", "蛙泳", "促使"}
	conn.Create(&u1)
}

//创建表
func CreateTable() {
	conn := DbConn()
	defer conn.Close()

	conn.AutoMigrate(&DepartmentInfo{})
	conn.AutoMigrate(&EmployeeInfo{})
	conn.AutoMigrate(&SupplierInfo{})
	conn.AutoMigrate(&DevicesType{})
	conn.AutoMigrate(&DevicesInfo{})
	conn.AutoMigrate(&DevicesLog2021{})

	//创建记录
	uid := universal.GetNumber()
	u1 := DevicesType{UID: uid, Name: "整机"}
	conn.Create(&u1)
}

//删除表
func DropTable() {
	conn := DbConn()
	defer conn.Close()

	conn.DropTable("user_info")
	conn.DropTable("supplier_info")
	conn.DropTable("employee_info")
	conn.DropTable("devices_type")
	conn.DropTable("devices_log2021")
	conn.DropTable("devices_info")
	conn.DropTable("department_info")

}

//创建数据
func CreateData(in_data interface{}) {
	conn := DbConn()
	defer conn.Close()

	//log.Printf("%v", in_data)
	//log.Printf("%T",in_data)
	//log.Println(reflect.TypeOf(in_data))

	switch in_data.(type) {
	case UserInfo:
		op, ok := in_data.(UserInfo)
		if ok == true {
			//log.Println(op)
			conn.Create(&op)
		}
	case SupplierInfo:
		op, ok := in_data.(SupplierInfo)
		if ok == true {
			//log.Println(op)
			conn.Create(&op)
		}
	default:
		log.Println("未定义结构体")
	}

}
